import { defineConfig, loadEnv } from "vite";
import vue from "@vitejs/plugin-vue";
//@
import path from "path";
//svg
import { createSvgIconsPlugin } from "vite-plugin-svg-icons";
//mock
import { viteMockServe } from "vite-plugin-mock";

//@ts-ignore
export default defineConfig((command, mode) => {
  //获取各种环境下的对应的变量
  let env = loadEnv(mode, process.cwd());
  return {
    plugins: [
      vue(),

      // SVG图标配置
      createSvgIconsPlugin({
        // Specify the icon folder to be cached
        iconDirs: [path.resolve(process.cwd(), "src/assets/icons")],
        // Specify symbolId format
        symbolId: "icon-[dir]-[name]",
      }),
      //mock
      viteMockServe({
        //@ts-ignore
        localEnabled: command === "serve", //开发阶段可以使用mock接口
      }),
    ],
    //src别名的配置
    resolve: {
      alias: {
        "@": path.resolve("./src"), // 相对路径别名配置，使用 @ 代替 src
      },
    },
    //scss全局变量
    css: {
      preprocessorOptions: {
        scss: {
          javascriptEnabled: true,
          additionalData: '@import "./src/styles/variable.scss";',
        },
      },
    }, //代理跨域
    server: {
      host: "0.0.0.0",
      port: 4000, //设置服务启动端口
      // open:true,    //设置服务启动时是否自动打开浏览器
      cors: true, //允许跨域
      proxy: {
        [env.VITE_APP_BASE_API]: {
          //获取数据的服务器地址设置
          target: env.VITE_SERVE,
          //需要代理跨域
          changeOrigin: true,
          //路径重写
          //rewrite: (path: string) => path.replace(/^\/api/, ""),
          rewrite: (path: string) =>
            path.replace(
              new RegExp("^" + env.VITE_APP_BASE_API), // ^/dev-api
              env.VITE_APP_TARGET_BASE_API // ""
            ), // 以 /dev-api 开头的请求转发至 target，示例： http://localhost:3000/dev-api/v1/users (F12可见) 代理转发 https://api.xxx.com/v1/users (真实接口地址)
        },
      },
    },
  };
});
